package com.zhaoj.savemoney.service;

import com.zhaoj.savemoney.ApplicationData;
import com.zhaoj.savemoney.utils.ConstantsUtils;

import cn.kuaipan.android.openapi.AuthSession;
import cn.kuaipan.android.openapi.KuaipanAPI;
import cn.kuaipan.android.openapi.session.AccessTokenPair;
import cn.kuaipan.android.openapi.session.AppKeyPair;
import cn.kuaipan.android.sdk.oauth.Session.Root;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;

public class LoadAndSyncDataService extends IntentService {
	private static final String APP_KEY = "" + "xc8vGOU1bMxGSdxF";
	private static final String APP_SECRET = "" + "YlrtbYeTLSrZJ8V8";

	private AuthSession mAuthSession;

	public LoadAndSyncDataService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	public LoadAndSyncDataService() {
		super("LoadAndSyncDataService");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		mAuthSession = buildSession();
		ApplicationData.mApi = new KuaipanAPI(
				ApplicationData.MainActivitycontext, mAuthSession);
		ApplicationData.mApi.startAuthForResult();
	}

	private AuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
		AuthSession session;

		String[] stored = getKeys();
		if (stored != null) {
			AccessTokenPair accessToken = new AccessTokenPair(stored[0],
					stored[1]);
			if (TextUtils.isEmpty(stored[2])) {

			}
			ApplicationData.authType = !TextUtils.isEmpty(stored[2]) ? Integer
					.valueOf(stored[2]) : 0;
			session = new AuthSession(appKeyPair, accessToken, Root.KUAIPAN);
			ApplicationData.authType = Integer.valueOf(stored[3]);
		} else {
			session = new AuthSession(appKeyPair, Root.KUAIPAN);
		}

		return session;
	}

	private String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(
				ConstantsUtils.ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ConstantsUtils.ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ConstantsUtils.ACCESS_SECRET_NAME,
				null);
		String uid = prefs.getString(ConstantsUtils.ACCESS_UID_NAME, null);
		String authType = prefs.getString(
				ConstantsUtils.ACCESS_AUTH_TYPE_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[4];
			ret[0] = key;
			ret[1] = secret;
			ret[2] = uid;
			ret[3] = authType;
			return ret;
		} else {
			return null;
		}
	}
}
